package com.sskj.uboex.ui.activity;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.SelfCoinBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.model.room.SelfCoinBeanViewModel;
import com.sskj.lib.util.CommonUtil;
import com.sskj.uboex.R;
import com.sskj.uboex.bean.SlideCoinBean;
import com.sskj.uboex.component.DaggerUserDataComponent;
import com.sskj.uboex.presenter.SelfChooseActivityPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.APP_SELF_CHOOSE)//自选
public class SelfChooseActivity extends BaseActivity<SelfChooseActivityPresenter> {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.llMsg)
    LinearLayout llMsg;
    private SlimAdapter<StockCoinBean> slimAdapter;
    private HashMap<String, Integer> coinMap;
    private Map<String, Disposable> timeMap = new HashMap<>();
    @Inject
    SelfCoinBeanViewModel selfCoinBeanViewModel;
    private List<SelfCoinBean> selfCoinBeanList;
    private boolean flag;

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_self_choose;
    }

    @Override
    public SelfChooseActivityPresenter getPresenter() {
        return new SelfChooseActivityPresenter();
    }

    @Override
    protected void initView() {
        DaggerUserDataComponent.create().inject(this);
        RxBus.getDefault().register(this);
        coinMap = new HashMap<>();
        coinMap.put("BTC/USDT", R.mipmap.app_icon_btc);
        coinMap.put("LTC/USDT", R.mipmap.app_icon_ltc);
        coinMap.put("EOS/USDT", R.mipmap.app_icon_eos);
        coinMap.put("ETC/USDT", R.mipmap.app_icon_etc);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_hangqing, new SlimInjector<StockCoinBean>() {
            @Override
            public void onInject(StockCoinBean data, IViewInjector injector, List payloads) {
                if (payloads == null || payloads.size() == 0) {
                    injector
                            .image(R.id.ivCoin, coinMap.get(data.getCode()) == null ? R.mipmap.app_icon_btc : coinMap.get(data.getCode()));

                }
                injector
                        .text(R.id.tvCoinName, data.getCode().substring(0, data.getCode().indexOf("/")))
                        .text(R.id.tvRate, data.getStockProductVO().getChangeRate())
                        .text(R.id.tvUSDT, String.format("USDT %s", CommonUtil.dealCoin(data.getStockProductVO().getPrice())))
                        .text(R.id.tvCNY, String.format("≈%s CNY", CommonUtil.dealCNY(data.getStockProductVO().getCnyPrice())))
                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.getStockProductVO().isUp() ? R.drawable.app_shape_corner30_ff3 : R.drawable.app_shape_corner30_05c))
                        .textColor(R.id.tvUSDT, data.getStockProductVO().isLight() ?
                                (getResources().getColor(data.getStockProductVO().isUp() ? R.color.app_f53 : R.color.app_05c)) :
                                getResources().getColor(R.color.app_1d2));
                ;
            }
        }).attachTo(recyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    ARouter.getInstance().build(RConfig.APP_MARKET_NEW).withString(Constans.CODE, slimAdapter.getDataItem(position).getCode()).navigation();
                });
        selfCoinBeanViewModel.getUsers().observe(this, selfCoinBeans -> {
            if (selfCoinBeans != null && selfCoinBeans.size() > 0) {
                selfCoinBeanList = selfCoinBeans;
                mPresenter.getData("USDT", false);
            }
        });
        ClickUtil.click(llMsg, () -> {
            ARouter.getInstance().build(RConfig.APP_MSG).navigation();
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(StockCoinBean.StockProductVOBean stockSocketBean) {


        if (slimAdapter != null) {
            Flowable.fromIterable(slimAdapter.getData())
                    .filter(item -> item.getStockProductVO().getCode().equals(stockSocketBean.getCode()))
                    .subscribe(item -> {
//                        if (Double.valueOf(stockSocketBean.getChange()) > 0) {
//                            stockSocketBean.setGreen(true);
//                        } else {
//                            stockSocketBean.setGreen(false);
//                        }
                        stockSocketBean.setLight(true);
                        item.setStockProductVO(stockSocketBean);
                        slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                        DisposUtil.close(timeMap.get(item.getStockProductVO().getCode()));
                        Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(i -> {
                                    item.getStockProductVO().setLight(false);
                                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                                });
                        timeMap.put(item.getStockProductVO().getCode(), subscribe);
                    }, e -> {
                    });
        }
    }

    public void updateCoin(List<StockCoinBean> data) {
        Flowable.fromIterable(data)
                .filter(stockCoinBean -> {
                    flag = false;
                    Flowable.fromIterable(selfCoinBeanList)
                            .filter(selfCoinBean -> selfCoinBean.getCode().equals(stockCoinBean.getCode()))
                            .subscribe(selfCoinBean -> {
                                flag = true;
                            });
                    return flag;
                })
                .toList()
                .subscribe(stockCoinBeans -> {
                    slimAdapter.updateData(stockCoinBeans);
                });
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
